// 加载 modules 模块
var http = require('http');
var express = require('express');
var app = express();
var server = http.Server(app);
var io = require('socket.io')(server);

// 加载 Demo
app.use(express.static('public'));

// 加载 local 模块
require('./helper/string.js');
var config = require('./config');
var common = require('./helper/common');

// 获取配置参数
var port = process.env.PORT || config.PORT;
var version = config.VERSION;

// 记录客户端集合
var clients = new Map();
// 记录用户集合
var users = new Map();

var resolveSocketId = function(socketid) {
    return socketid.split('/#').join('');
};

/**
 * 检测对象有效性
 */
var isValidObject = function(obj) {
    if (typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length) {
        return true;
    } else {
        return false;
    }
};

/**
 * 检测用户数据
 * @param pid [用户Id]
 * @param pname [用户姓名]
 */
var checkUserData = function(data) {
    if (isValidObject(data)) {
        if (data.hasOwnProperty('uid')) {
            return false;
        }
        if (data.hasOwnProperty('pid') && data.hasOwnProperty('pname')) {
            return true;
        }
    }
    return false;
};

/**
 * 客户端上线
 */
io.on('connection', function(socket) {
    var token = resolveSocketId(socket.id);
    clients.set(token, socket);
    console.log('A user [%s] connection.', token);
    socket.emit('connectSuccess', { 'token': token });

    /**
     * 客户端登录
     */
    socket.on('userSignin', function(data) {
        if (checkUserData(data) == false) {
            console.log('Invalid user object.');
            return false;
        }
        // console.log('A user signin:' + JSON.stringify(data));
        var room = data.room || 'default';
        data.room = room;
        data.uid = token;

        if (users.get(token)) {
            return false;
        }
        socket.join(room);
        users.set(token, data);
        io.sockets.to(room).emit('userSigninSuccess', data);
    });

    socket.on('startPushStream', function(data) {
        if (!isValidObject(data)) {
            console.log('Invalid chat object.');
            return false;
        }
        if (!data.hasOwnProperty('stream') || data.stream == '') {
            console.log('Stream address is empty.');
            return false;
        }
        var user = users.get(token);
        if (user) {
            io.emit('startPushStreamResult', data);
        } else {
            socket.emit('startPushStreamResult', 'Invalid user, please login first.');
        }
    });

    socket.on('stopPushStream', function() {
        io.emit('stopPushStreamResult');
    });

    /**
     * 客户端下线
     */
    socket.on('disconnect', function() {
        console.log('Client [%s] disconnect:', token);
        var user = users.get(token);
        if (user == null) {
            return;
        }
        socket.leave(user.room);
        //广播用户掉线
        io.sockets.to(user.room).emit('userDisconnect', user);
        users.delete(token);
        clients.delete(token);
    });
});

// 启动服务
server.listen(port, function() {
    console.log('通讯服务 %s', version);
    console.log('Server listening at port %d in %s.', port, common.now());
});